package org.friut.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * Abstract action
 * 
 * @author Tang 
 * @since 2012/9/22
 */
public abstract class AbstractAuthAction extends ActionSupport {
	
	private static final long serialVersionUID = 5986347172924935386L;
	
	// Format
	protected static final String FORMAT_HTML_UTF8   = "text/html;charset=utf-8";
	protected static final String FORMAT_HTML_GB2312 = "text/html;charset=gb2312";
	protected static final String FORMAT_XML         = "application/xml;charset=UTF-8";
	protected static final String FORMAT_JSON        = "application/json;charset=UTF-8";
	
	// Get session
	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	// Get response
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	// Get request
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * Send JSON data
	 * 
	 * @param json
	 */
	protected void sendJsonResponse(String json) {
		getResponse().setContentType(FORMAT_JSON);
		
		PrintWriter writer = null;
		try {
			writer = getResponse().getWriter();
		} catch (IOException e) {
			LOG.error("Send json response error. {}", e.getMessage());
		}
		writer.print(json);
		writer.close();
	}
	
	/**
	 * Require parameters
	 * 
	 * @param args
	 */
	protected boolean requireParameters(String... args) {
		for (String parameter : args) {
			if (!getRequest().getParameterMap().containsKey(parameter)) {
				sendJsonResponse("Required parameter invalid : " + parameter);
				LOG.error("Required parameter invalid.{}", parameter);
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Get HTTP connection IP
	 * 
	 * @return
	 */
	public String getHttpConnectionIp () {
		return getRequest().getLocalAddr();
	}
}
